package com.font.web.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.font.bean.Face;
import com.font.bean.ParamResult;
import com.font.bean.SysUser;
import com.font.bean.result.Result;
import com.font.service.FaceService;
import com.font.service.SysUserService;
import com.font.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/system")
public class UserController {
    @Autowired
    SysUserService userService;
    @Autowired
    FaceService faceService;

   @GetMapping("/userobj")
    public Result userobj(String name){
       System.err.println(name);
       SysUser obj = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getNickName, name));
       Face one = faceService.getOne(new LambdaQueryWrapper<Face>().eq(Face::getFaceName, obj.getUserName()));
       Map<String, Object> map = new HashMap<>();
       map.put("user",obj);map.put("face",one);
       return Result.success(map);
    }

    @PostMapping("/updateobbj")
    public Result updateobbj(@RequestBody SysUser user){

        boolean b = userService.updateById(user);
        return Result.success( b );
    }

    @GetMapping("/updatePassword")
    public Result updatePassword(@RequestParam(value = "userId" )String userId,
                                 @RequestParam(value = "userName" )String userName,
                                 @RequestParam(value = "newpass" )String newpass,
                                 @RequestParam(value = "oldpass" )String oldpass){

        Face one = faceService.getOne(new LambdaQueryWrapper<Face>().eq(Face::getFaceName, userName));
//        System.err.println(MD5.encrypt(oldpass).equals(one.getPassWord()));
        if ( MD5.encrypt(oldpass).equals(one.getPassWord())){
            Face face = new Face();face.setFaceName(userName);face.setPassWord(MD5.encrypt(newpass));
            faceService.update(face,new LambdaQueryWrapper<Face>().eq(Face::getFaceName,userName));
        }

        return Result.success(MD5.encrypt(oldpass).equals(one.getPassWord()));
    }

    @Value("${file.uploadFolder}")
    private String  address ;
    SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload/{userId}")
    public Map<String,Object> fileUpload(MultipartFile file, HttpServletRequest request,@PathVariable(value = "userId")Long userId) throws IOException {


        Map<String,Object> result=new HashMap<>();
        String originalFilename = file.getOriginalFilename();
        if (file.getSize() == 0) {
            result.put("status","error");
            result.put("msg","文件为空");
            return  result;
        }
        if(!originalFilename.endsWith(".jpg")){
            result.put("status","error");
            result.put("msg","文件类型不对");
            return  result;
        }

        String format=sdf.format(new Date());
        String realpath1 = request.getServletContext().getRealPath("/") + format;
        String realpath = address + format;
        File folder = new File(realpath);
        if (!folder.exists()){
            folder.mkdirs();
        }

        String newName=  UUID.randomUUID().toString()+".jpg";
        try {
            file.transferTo(new File(folder,newName));
            String url = "/profile/avatar"+ format + newName;
            SysUser sysUser = new SysUser();sysUser.setUserId(userId);sysUser.setAvatar(url);
            userService.updateById(sysUser);
            result.put("status","success");
            result.put("url",url);
            return  result;
        } catch (Exception e) {
            result.put("status","error");
            result.put("msg",e.getMessage());
        }
        return result;
    }
}
